import json
import os.path
import time
from datetime import datetime

import numpy

from project_budget.settings.base import BASE_DIR
import pandas as pd

from typing import List, Dict, Optional, Tuple
from django.http import QueryDict
from django.http import JsonResponse
from django.views import View

from plotly.utils import PlotlyJSONEncoder
import plotly.graph_objects as go
import plotly.io as pio

from project_budget.settings.base import BASE_DIR
from .models import *
from rest_framework_simplejwt.authentication import JWTAuthentication

# 职位信息
class PositionInfo(View):
    def get(self, request):
        page = request.GET.get('page', 1)
        pageSize = request.GET.get('pageSize', 5)
        page = int(page)
        pagesize = int(pageSize)
        start = (page - 1) * pagesize
        end = start + pagesize
        data = Position.objects.filter(status=True)[start:end].values()
        return JsonResponse({'msg': '成功', "code": 200, 'list': list(data)})

    def post(self, request):
        try:
            data = json.loads(request.body)
        except:
            return JsonResponse({'code': '400', 'msg': '检查接口文档数据'})
        Position.objects.create(**data)
        return JsonResponse({'msg': '添加成功', "code": 200})

    def put(self, request):
        try:
            data = json.loads(request.body)
        except:
            return JsonResponse({'code': '400', 'msg': '检查接口文档数据'})
        merList = data.get("mergeList")
        if isinstance(merList, str):
            merList = json.loads(merList)
        produs = Position.objects.filter(id__in=merList)
        produs.update(status=False)
        Position.objects.create(jobName=data['jobName'], department_id=data['department_id'],
                                job=data['job'], rank=data['rank'], peopleNum=data['peopleNum'])
        return JsonResponse({'msg': '修改成功', "code": 200})

    def delete(self, request):
        try:
            data = json.loads(request.body.decode())
        except:
            return JsonResponse({'code': '400', 'msg': '检查接口文档数据'})
        data = data.get("checkList")
        if isinstance(data, str):
            data = json.loads(data)
        list = Position.objects.filter(id__in=data)
        list.update(status=False)
        return JsonResponse({'msg': '删除成功', "code": 200})


# 部门信息
class DepartmentView(View):
    def get(self, res):
        page = res.GET.get('page', 1)
        pageSize = res.GET.get('pageSize', 5)
        page = int(page)
        pagesize = int(pageSize)
        start = (page - 1) * pagesize
        end = start + pagesize
        department = Department.objects.filter(status=True)[start:end].values()
        return JsonResponse({'msg': '成功', "code": 200, 'list': list(department)})

    def post(self, res):
        try:
            data = json.loads(res.body)
        except:
            return JsonResponse({'code': '400', 'data': '检查接口文档数据'})
        try:
            Department.objects.create(**data)
        except:
            return JsonResponse({'code': 400, 'data': '检查数据格式'})
        return JsonResponse({'code': 201})

    def delete(self, res):
        try:
            data = json.loads((res.body).decode())
        except:
            return JsonResponse({'code': '400', 'data': '检查接口文档数据'})
        data = data.get('checkBoxList')
        if isinstance(data, str):
            data = json.loads(data)
        department = Department.objects.filter(id__in=data)
        department.update(status=False)
        return JsonResponse({'msg': '成功', "code": 200})

    def put(self, res):
        try:
            data = json.loads((res.body).decode())
        except:
            return JsonResponse({'code': '400', 'data': '检查接口文档数据'})
        department = Department.objects.filter(id=data.get('id'))
        del data['id']
        department.update(**data)
        return JsonResponse({'code': 200, 'msg': '成功'})

    def patch(self, res):
        try:
            data = json.loads((res.body).decode())
        except:
            return JsonResponse({'code': '400', 'data': '检查接口文档数据'})

        department = Department.objects.filter(id__in=data.get('checkBoxList'))
        department.update(status=False)
        del data['checkBoxList']
        Department.objects.create(**data)
        return JsonResponse({'code': 202, 'msg': '成功'})


# 获取 分类 - 无限极分类
def getParentClassify(req):
    page = req.GET.get('page')
    pagesize = req.GET.get('pageSize')

    questList = MaterialsClassify.objects.filter(status=1).values()

    tree = {}
    li = []
    for i in questList:
        tree[i['id']] = i  # 将所有的分类先存到一个字典中，key为当前的id
    try:
        for i in questList:
            # 如果当前是顶级分类
            if i['pid'] == '0':
                pfenlei = tree.get(i['id'])
                li.append(pfenlei)

        # 顶级分类添加完成后寻找对应子分类
        for i in questList:
            if i['pid'] != '0':
                if 'children' not in tree[int(i['pid'])]:
                    tree[int(i['pid'])]['children'] = []
                tree[int(i['pid'])]['children'].append(tree[int(i['id'])])
    except:
        return JsonResponse({"state": 400, "message": "分类异常"}, safe=False, json_dumps_params={'ensure_ascii': False})

    # 如果传入page 和 pagesize 则为分页获取分类
    if page and pagesize:
        page = int(page)
        pagesize = int(pagesize)
        start = (page - 1) * pagesize
        end = start + pagesize
        # 截取
        li = li[start:end]

    total = MaterialsClassify.objects.filter(level=1, status=1).count()
    data = {
        'list': li,
        'state': 200,
        'total': total,
        'message': 'OK'
    }
    return JsonResponse(data, safe=False, json_dumps_params={'ensure_ascii': False})


# 创建模板
def createTemplate(req):
    file = req.FILES.get('file')

    name = req.POST.get('name')
    explain = req.POST.get('explain')
    temp_status = req.POST.get('temp_status')

    if not file:
        return JsonResponse({'status': 408, 'message': 'excel上传失败！'})

    # 文件名称
    fileName = f"{time.time()}_{file.name}"

    # 文件路径
    pathUrl = os.path.join(BASE_DIR, 'static', 'template', fileName)
    # print(pathUrl)
    try:
        with open(pathUrl, 'wb') as f:
            f.write(file.read())

    except:
        return JsonResponse({'status': 409, 'message': 'excel模板有误！'})

    df = pd.read_excel(pathUrl, sheet_name=0, header=1)
    title = df.columns
    title = {
        "title": ["日期", *title]
    }
    df1 = df.values
    # df1 = json.dumps(df1)
    df1 = json.dumps(df1.tolist())
    # print(df1)
    filedata = {
        'file_excel': f"static/template/{fileName}",
        'file_data': df1,
    }
    file = json.dumps(filedata)
    try:
        Template.objects.create(name=name, explain=explain, temp_status=temp_status, file=file, file_title=json.dumps(title))
    except:
        return JsonResponse({'status': 400, 'message': '参数有误！'})
    return JsonResponse({'status': 200, 'message': '成功'})


# 读取模板
def ReadTemplate(req):
    t_id = req.GET.get('tid')
    # print(t_id)
    data = Template.objects.filter(id=t_id).values()
    dd = json.loads(data[0]['file'])
    xq_data = json.loads(numpy.array(dd['file_data']).tostring())
    path_list = str(dd['file_excel']).split('/')
    path = os.path.join(BASE_DIR, 'static', 'template', path_list[2])
    df = pd.read_excel(path, sheet_name=0, header=1)
    title = df.iloc[0]
    title = list(title.index)
    tableHeader = [
        {'id': 1, 'eli': 'data', 'title': '日期'},
        {'id': 2, 'eli': 'seatnumber', 'title': '楼座号'},
        {'id': 3, 'eli': 'empty', 'title': ''},

    ]
    for tab in range(len(title) - 2):
        table_dict = {'id': tab + 4, 'eli': 'tower' + str(tab + 4), 'title': title[tab + 2]}
        tableHeader.append(table_dict)
    tableData = []

    for h in range(len(xq_data)):
        data_dict = {
            'id': h + 1,
            'data': datetime.now(),
            'modData': False,
            'seatnumber': xq_data[h][0],
            'empty': xq_data[h][1],
            'tower4': xq_data[h][2],
            'tower5': xq_data[h][3],
            'tower6': xq_data[h][4],
            'tower7': xq_data[h][5],
            'tower8': xq_data[h][6],
            'tower9': xq_data[h][7],
            'tower10': xq_data[h][8],
            'tower11': xq_data[h][9],
            'tower12': xq_data[h][10],
            'tower13': xq_data[h][11],
            'tower14': xq_data[h][12],
            'tower15': xq_data[h][13],
        }
        tableData.append(data_dict)
    return JsonResponse({
        'status': 200,
        'message': '成功',
        'tableHeader': list(tableHeader),
        'tableData': list(tableData),
    })


# 删除模板
def delTemplate(request):
    del_list = request.GET.get('del_list')
    did = request.GET.get('did')
    if del_list is None:
        try:
            data = Template.objects.filter(id=did).values()
            dd = json.loads(data[0]['file'])
            path_list = str(dd['file_excel']).split('/')
            path = os.path.join(BASE_DIR, 'static', 'template', path_list[2])
            os.remove(path)
            Template.objects.get(id=did).delete()
        except:
            return JsonResponse({'msg': "删除失败", 'code': 400, 'data': '存在关联数据；不允许删除'})
        return JsonResponse({'msg': "删除成功", 'code': 200})
    if did is None:
        #  修改status状态  和关联该数据的状态    获取数据也需要根据status获取
        del_list = json.loads(del_list)
        try:
            for i in (del_list):
                data = Template.objects.filter(id=i).values()
                for d in data:
                    dd = json.loads(d['file'])
                    path_list = str(dd['file_excel']).split('/')
                    path = os.path.join(BASE_DIR, 'static', 'template', path_list[2])
                    os.remove(path)
                Template.objects.get(id=i).delete()
        except:
            return JsonResponse({'msg': "批量删除失败", 'code': 400, 'data': '存在关联数据；不允许删除'})
        return JsonResponse({'msg': "批量删除成功", 'code': 200})


#
class UpdateTemplate(View):
    def get(self, req):

        id = req.GET.get('uid')
        data = Template.objects.filter(id=id).values()

        return JsonResponse({
            'message': '获取模板信息',
            'status': 200,
            'data': list(data)

        })


    def put(self, req):
        dd = json.loads(req.body)
        # print(dd)
        Template.objects.filter(id=dd['uid']).update(temp_status=dd['status'])

    def post(self, req):

        return JsonResponse({
            'message': '修改模板状态成功',
            'status': 200,

        })

# 库存数据
class Register(View):
    def get(self,req):
        try:
            # 第几页
            pagenum = int(req.GET.get('pagenum'))
            # 每页多少条
            pagesize = int(req.GET.get('pagesize'))
            # 创建时间
            update_time = req.GET.get('update_time')

            if update_time == None:


                # 获去库存的所以数据
                lis=Store.objects.all().values()
                for i in lis:
                    # 遍历获取所有数据的id
                    L=Store.objects.filter(id=i['id'])
                    # 循环库存对应的id
                    for y in L:
                        # 获取库存对应的材料
                        duiyingcailiao=y.store_materials_set.values('materials_status','materials_price','materials_num')
                        if len(duiyingcailiao)==0:
                            continue
                        else:
                            # 库存对应材料的总价格
                            allprice=0
                            # 库存对应材料的总数
                            allnum=0
                            # 对材料类进行总数的查询

                            for x in list(duiyingcailiao):
                                if x['materials_status']==False:
                                    continue
                                else:
                                    allnum+=int(x['materials_num'])
                                    allprice+=int(x['materials_price'])
                                    # print(x['materials_price'],x['materials_num'])
                            Store.objects.filter(id=i['id']).update(all_price=allprice,all_num=allnum)

                getstore = list(Store.objects.all()[((pagenum - 1) * pagesize):(pagenum * pagesize)].values())
                count = Store.objects.all().count()
            else:
                getstore = list(Store.objects.filter(create_time__contains=update_time)[
                                ((pagenum - 1) * pagesize):(pagenum * pagesize)].values())
                count = Store.objects.filter(update_time__contains=update_time).count()
        except:
            return JsonResponse({'status':201,'message':'检查接口文档数据'})
        return JsonResponse({'data':getstore,'count':count,'status':200})

    def post(self, req):
        try:
            da = json.loads(req.body)
            Store.objects.create(**da)
        except:
            return JsonResponse({'status': 201, 'message': '检查接口文档数据'})
        return JsonResponse({'status': 200, 'message': '新增成功'})

    def put(self, req):

        try:
            da = json.loads(req.body)

            # if (da['all_price']<0 or da['all_num']<0) or (da['all_price']<0 and da['all_num']<0):
            #
            #     return JsonResponse({'status': 201, 'message': '检查接口文档数据'})

            Store.objects.filter(id=da['id']).update(**da)
        except:
            return JsonResponse({'status':201,'message':'检查接口文档数据'})

        return JsonResponse({'status':200,'message':'修改成功'})
    def delete(self,req):
        try:
            lis = json.loads(req.body)
            ids = lis['ids']
            Store.objects.filter(id__in=ids).delete()
        except:
            return JsonResponse({'status': 201, 'message': '请查看接口文档数据'})
        return JsonResponse({'status':200,'message':'删除成功'})

# 库存材料
class storeMaterials(View):

    def get(self,req):
        try:
            # 第几页
            pagenum = int(req.GET.get('pagenum'))

            # 每页多少条
            pagesize = int(req.GET.get('pagesize'))
            # 搜索
            update_time = req.GET.get('update_time')

            # store_id仓库id

            storeId=int(req.GET.get('store_id'))

            store = Store.objects.filter(id=storeId)
            lis = []
            count = 0

            if update_time == None:

                for i in store:
                    # 获取库存对应的材料
                    lis=i.store_materials_set.values()[((pagenum - 1) * pagesize):(pagenum * pagesize)]
                    #获取库存对应材料的数量
                    count=i.store_materials_set.all().count()
                # print(store.store_materials_set.values())
                # print(store.store_materials_set.name)
                #     return JsonResponse({'status': 200, 'message': '获取成功', 'data': list(lisOne), 'count': countOne})
                # lis=Store_Materials.objects.all()[((pagenum - 1) * pagesize):(pagenum * pagesize)].values()
                # count=Store_Materials.objects.all().count()


            else:
                for i in store:
                    # print(update_time,'搜索')
                    shechVal=i.store_materials_set.all()
                    # print(i.store_materials_set.values())
                    for x in shechVal:
                        # print(update_time,str(x.update_time))
                        # print(update_time in str(x.update_time))
                        if update_time in str(x.update_time):
                            Sid=x.id
                            StoreData=Store_Materials.objects.filter(id=Sid).values()
                            lis.append(StoreData[0])
                count = len(lis)
                lis=lis[((pagenum - 1) * pagesize):(pagenum * pagesize)]

                            # print(x.name,'??')
                            # print(i.store_materials_set.all().count(), '??')
                        # print(x.update_time,'fool 循环')
                # print(list(lis),'lis')
                # lis=Store_Materials.objects.filter(update_time__contains=update_time)[((pagenum - 1) * pagesize):(pagenum * pagesize)].values()
                # count=Store_Materials.objects.filter(update_time__contains=update_time).count()
        except:
            return JsonResponse({'status':201,'message':'检查接口文档数据'})

        return JsonResponse({'status':200,'message':'获取成功','data':list(lis),'count':count})

    def post(self, req):
        try:
            lis=json.loads(req.body)
            # 获取材料id
            materials_id=lis['materials_id']
            # 查出对应材料
            materials=ProjectMaterials.objects.filter(id=materials_id).values()[0]

            # 获取材料的name
            materials_name=materials['name']
            lis['name'] = materials_name
            # 获取材料的价格
            materials_price=int(materials['price'])
            # 获取材料的数量
            num=int(lis['materials_num'])
            # 计算材料的总价格
            lis['materials_price'] = num*materials_price

            # 获取分类的name
            materials_type=ProjectMaterials.objects.filter(id=materials_id).values('materialsClassify__name')[0]["materialsClassify__name"]
            lis['materials_type'] = materials_type


            # 获取仓库名称
            store_name=Store.objects.filter(id=lis['store_id']).values()[0]
            store_name=store_name['name']
            # 添加入库信息
            StorageMessage.objects.create(store_name=store_name,
                                          materials_name=lis['name'],
                                          store_coome_num=num,
                                          materials_price=materials_price,
                                          store_id=lis['store_id']
                                          )
            # 判断材料的数量和价格不能为负值
            if (materials_price<0 and num<0) or (materials_price<0 or num<0):
                return JsonResponse({'status': 201, 'message': '检查接口文档数据'})
            # 判断添加的类是否重复
            judgeMaterials_id=Store_Materials.objects.filter(materials_id=materials_id).values()

            if len(judgeMaterials_id)==0:
                # 添加到库存对应的材料里
                Store_Materials.objects.create(**lis)
            else:
                # 如果这个材料有只加数量
                # 获取当前的总价
                zongjia=Store_Materials.objects.filter(materials_id=materials_id).values()
                endNum=zongjia[0]['materials_num']
                # 之前材料总价
                endPrice=zongjia[0]['materials_price']
                #  现在材料的总价
                numPrice=int(num*materials_price)

                # 最新总价
                allPrice=int(endPrice)+int(numPrice)

                # 最新数量
                nuwNum=int(endNum)+int(num)
                lis['materials_price']=allPrice
                lis['materials_num'] = nuwNum
                # print(materials_id,'测试')
                Store_Materials.objects.filter(materials_id=materials_id).update(**lis)


        except:
            return JsonResponse({'status': 201, 'message': '检查接口文档数据'})

        return JsonResponse({'status': 200, 'message': '添加成功'})

    def put(self, req):

        try:
            da=json.loads(req.body)
            S=Store.objects.filter(id=da['store_id'])

            putId=0
            for i in S:
                store_data=i.store_materials_set.all().values()
                for x in store_data:

                    # print(da['materials_id'],x['materials_id'])
                    if int(da['materials_id'])==int(x['materials_id']):
                        putId=x['id']
            # print(putId)

            # 获取库存对应材料信息
            lis=Store_Materials.objects.filter(id=putId).values()[0]

            # 获取材料单价
            materialPriceVal=ProjectMaterials.objects.filter(id=da['materials_id']).values()[0]
            materialPrice=materialPriceVal['price']
            # 获取材料总价格
            material_all_prcie=lis['materials_price']
            # 获取材料总数量
            materials_all_num=lis['materials_num']
            # 获取需要减少材料的数量
            reauce_num=da['reduce_materials_num']

            #材料总量减需要减少的数量
            newNum=int(materials_all_num)-int(reauce_num)
            # 要减少材料的总金额
            newPrice=int(material_all_prcie)-int(int(reauce_num)*int(materialPrice))

            # 先获取材料对应的库的name
            oneHuoquDate=Store_Materials.objects.filter(materials_id=da['materials_id']).values('store__name','store__id')
            oneHuoquName=oneHuoquDate[0]['store__name']
            oneHuoquId=oneHuoquDate[0]['store__id']



            jwt_obj = JWTAuthentication()
            tokens = req.META.get("HTTP_AUTHORIZATION").split(" ")[1]
            validated_token = jwt_obj.get_validated_token(tokens)
            user = jwt_obj.get_user(validated_token)

            # print(oneHuoqu, reauce_num, materialPrice, lis['name'], da['remark'],user)
            # 出库总金额
            remmove_price=int(reauce_num)*int(materialPrice)

            StorageRemoval.objects.create(store_name=oneHuoquName,
                                          materials_name=lis['name'],
                                          store_removal_num=reauce_num,
                                          operator=user,
                                          remark=da['remark'],
                                          store_id=oneHuoquId,
                                          all_price=remmove_price
                                          )

            if newNum ==0:
                Store_Materials.objects.filter(materials_id=da['materials_id']).delete()
            elif newNum<0:
                return JsonResponse({'status': 202, 'message': '数量超出库存数量'})
            else:

                Store_Materials.objects.filter(materials_id=da['materials_id']).update(materials_num=newNum,materials_price=newPrice)
        except:
            return JsonResponse({'status': 201, 'message': '检查接口文档数据'})

        return JsonResponse({'status': 200, 'message': '修改成功'})

    def delete(self, req):

        try:

            da = json.loads(req.body)
            ids=da['ids']
            store_id=da['store_id']
            StoreDate=Store.objects.filter(id=store_id)
            for i in StoreDate:
                y=i.store_materials_set.all().values()
                for x in y:
                    if x['id'] in ids:
                        Store_Materials.objects.filter(id=x['id']).delete()

        except:
            return JsonResponse({'status': 201, 'message': '请查看接口文档数据'})


        return JsonResponse({'status': 200, 'message': '删除成功'})




class ProjectListsView(View):
    def get(self, request):
        # 第几页
        pagenum = int(request.GET.get('pagenum',1))
        # 每页多少条
        pagesize = int(request.GET.get('pagesize',1))
        # 循环工程列表
        prolist = ProjectList.objects.all()
        data = []

        for pro in prolist:
            storelist = []
            for store in pro.store.all():
                # materials_list = []
                # for material in materials_list_set:
                #     materials_list.append({
                #
                #     })
                storelist.append({
                    "store_name": store.name,
                    "time_update": store.update_time,
                    "all_price": store.all_price,
                    "all_num": store.all_num,
                    "store_status": store.store_status,
                    "materials_list": list(store.store_materials_set.all().values())
                })

                # print(json.loads(Template.objects.get(id=12).file))
                dd = json.loads(Template.objects.get(id=12).file)

                # print(json.loads(numpy.array(dd['file_data']).tostring()))
                aimlist = json.loads(numpy.array(dd['file_data']).tostring())
                yujing_money = 0
                all_money = 0
                print(aimlist[0][7])
                for i in aimlist[1:]:
                    if i[7] != numpy.nan:
                        if str(i[7]).isdigit():
                            yujing_money += float(i[7])
                    if i[6] != numpy.nan:
                        if str(i[6]).isdigit():
                            all_money += float(i[6])

            data.append({
                "id": pro.id,
                "name": pro.project.name,
                "template": Template.objects.get(id=int(pro.template_id)).name,
                "site": pro.project.site,
                "people": pro.people_name,
                "template_id": int(pro.template_id),
                "storelist": storelist,
                "yujing_money": yujing_money,
                "all_money": all_money
            })
        total = len(data)
        data = data[(pagenum-1)*pagesize:(pagenum)*pagesize]
        return JsonResponse({"total":total,"data": list(data)})

    def post(self, request):
        data = json.loads(request.body)
        kk = ProjectList.objects.create(people_name=data['people_name'], project_id=data['project_id'],
                                        template_id=data['template_id'])
        for i in data['store_id']:
            print(i)
            kk.store.add(Store.objects.get(id=int(i)))
        return JsonResponse({"data": data})

    def put(self,request):
        data = json.loads(request.body)
        # print(data["list_id"])
        aimlist = ProjectList.objects.get(id=data['id'])
        aimlist.name = data['people_name']
        aimlist.project_id = data['project_id']
        aimlist.template_id = data['template_id']
        aimlist.store.clear()
        for i in data['store_id']:
            aimlist.store.add(Store.objects.get(id=i))
        aimlist.store.create()

        aimlist.save()
        return JsonResponse({"status": 200,"data":{"message":"修改成功"}})

    def delete(self,request):
        list_id = request.GET.get("list_id")
        aimlist = ProjectList.objects.get(id=list_id)
        aimlist.delete()
        return JsonResponse({"status": 200,"data":{"message":"删除成功"}})


class Daoru(View):
    def post(self,request):
        file = request.FILES.get('file')
        print(request.FILES)
        # data = json.loads(request.body)
        if not file:
            return JsonResponse({'status': 408, 'message': 'excel上传失败！'})

            # 文件名称
        fileName = f"{time.time()}_{file.name}"

        # 文件路径
        pathUrl = os.path.join(BASE_DIR, 'static', 'template', fileName)
        print(file.read())
        try:
            with open(pathUrl, 'wb') as f:
                f.write(file.read())

        except:
            return JsonResponse({'status': 409, 'message': 'excel模板有误！'})

        df = pd.read_excel(pathUrl, sheet_name=0, header=1)
        title = df.columns # 标题
        title = ["日期", *title]
        filedata = df.values # 数据
        tableHeader = [
            {'id': 1, 'eli': 'data', 'title': '日期'},
            {'id': 2, 'eli': 'seatnumber', 'title': '楼座号'},
            {'id': 3, 'eli': 'empty', 'title': ''},

        ]
        for tab in range(len(title) - 3):
            table_dict = {'id': tab + 4, 'eli': 'tower' + str(tab + 4), 'title': title[tab + 2]}
            tableHeader.append(table_dict)
        tableData = []
        budget_money = 0
        actual_money = 0
        for h in range(len(filedata)):
            if str(filedata[h][7]) != "nan":
                budget_money += float(filedata[h][7])
            if str(filedata[h][9]) != "nan":
                actual_money += float(filedata[h][9])
            data_dict = {
                'id': h + 1,
                'data': datetime.now(),
                'modData': False,
                'seatnumber': filedata[h][0],
                'empty': filedata[h][1],
                'tower4': filedata[h][2],
                'tower5': filedata[h][3],
                'tower6': filedata[h][4],
                'tower7': filedata[h][5],
                'tower8': filedata[h][6],
                'tower9': filedata[h][7],
                'tower10': filedata[h][8],
                'tower11': filedata[h][9],
                'tower12': filedata[h][10],
                'tower13': filedata[h][11],
                'tower14': filedata[h][12],
                'tower15': filedata[h][13],
            }
            tableData.append(data_dict)

        return JsonResponse({
            "status": 200,
            "message": '成功',
            "tableHeader": list(tableHeader),
            "tableData": list(tableData),
            "budget_money": budget_money,
            "actual_money": actual_money,
            "over_money": actual_money - budget_money
        })

class GetTemplateViews(View):
    def get(self, request):
        tid = request.GET.get("tid")
        aimlist = ProjectList.objects.get(id=tid)
        aimfile = Template.objects.filter(id=int(aimlist.template_id)).values()
        dd = json.loads(aimfile[0]['file'])

        path_list = str(dd['file_excel']).split('/')
        path = os.path.join(BASE_DIR, 'static', 'template', path_list[2])
        # df = pd.read_excel(path, sheet_name=0, header=1)
        # title = df.iloc[0]
        # title = list(title.index)
        title = json.loads(aimfile[0]['file_title'])
        title = title['title']

        filedata = json.loads(numpy.array(dd['file_data']).tostring())
        tableHeader = [
            {'id': 1, 'eli': 'data', 'title': '日期'},
            {'id': 2, 'eli': 'seatnumber', 'title': '楼座号'},
            {'id': 3, 'eli': 'empty', 'title': ''},
        ]
        for tab in range(len(title) - 3):
            table_dict = {'id': tab + 4, 'eli': 'tower' + str(tab + 4), 'title': title[tab + 2]}
            tableHeader.append(table_dict)
        tableData = []

        budget_money = 0
        actual_money = 0
        for h in range(len(filedata)):
            if str(filedata[h][7]) != "nan":
                if str(filedata[h][7]).isdigit():
                    budget_money += float(filedata[h][7])
            if str(filedata[h][9]) != "nan":
                if str(filedata[h][9]).isdigit():
                    actual_money += float(filedata[h][9])
            data_dict = {
                'id': h + 1,
                'data': datetime.now(),
                'modData': False,
                'seatnumber': filedata[h][0],
                'empty': filedata[h][1],
                'tower4': filedata[h][2],
                'tower5': filedata[h][3],
                'tower6': filedata[h][4],
                'tower7': filedata[h][5],
                'tower8': filedata[h][6],
                'tower9': filedata[h][7],
                'tower10': filedata[h][8],
                'tower11': filedata[h][9],
                'tower12': filedata[h][10],
                'tower13': filedata[h][11],
                'tower14': filedata[h][12],
                'tower15': filedata[h][13],
            }
            tableData.append(data_dict)
        return JsonResponse({
            "status": 200,
            "message": '成功',
            "tableHeader": list(tableHeader),
            "tableData": list(tableData),
            "budget_money": budget_money,
            "actual_money": actual_money,
            "over_money": actual_money - budget_money
        })

    def post(self,request):
        data = json.loads(request.body)
        typea = data['type']
        aimid = data["list_id"]
        aimlist = ProjectList.objects.get(id=aimid)
        aimfile = Template.objects.filter(id=int(aimlist.template_id)).values()


        dd = json.loads(aimfile[0]['file'])
        filedata = json.loads(numpy.array(dd['file_data']).tostring())

        if typea==0:
            if len(data['addlist']) == len(filedata[0]):
                filedata.append(data['addlist'])
                # print(filedata)
                finallist = Template.objects.get(id=int(aimlist.template_id))
                temp = json.loads(finallist.file)
                temp['file_data'] = json.dumps(filedata)
                finallist.file = json.dumps(temp)
                finallist.save()

                return JsonResponse({"status": 200,"message":"添加成功！"})
            else:
                return JsonResponse({"status": 400,"message":"数组长度不符,长度应为:{},接收到的:{}".format(len(filedata[0]),len(data['addlist']))})
        else:
            if len(data['addlist']) == len(filedata):
                for i in range(len(filedata)):
                    filedata[i].append(data['addlist'][i])
                # print(filedata)
                finallist = Template.objects.get(id=int(aimlist.template_id))
                temp = json.loads(finallist.file)
                temp['file_data'] = json.dumps(filedata)
                finallist.file = json.dumps(temp)
                finallist.save()

                return JsonResponse({"status": 200, "message": "添加成功！"})
            else:
                return JsonResponse(
                    {"status": 400, "message": "数组长度不符,长度应为:{},接收到的:{}".format(len(filedata), len(data['addlist']))})

    def delete(self,request):
        typea = request.GET.get("type")
        aimid = request.GET.get("list_id")
        aimindex = int(request.GET.get("aimindex"))
        aimlist = ProjectList.objects.get(id=aimid)
        aimfile = Template.objects.filter(id=int(aimlist.template_id)).values()


        dd = json.loads(aimfile[0]['file'])
        filedata = json.loads(numpy.array(dd['file_data']).tostring())

        if typea==0 or typea=='0':
            if aimindex < len(filedata):
                filedata.pop(aimindex)
                finallist = Template.objects.get(id=int(aimlist.template_id))
                temp = json.loads(finallist.file)
                temp['file_data'] = json.dumps(filedata)
                finallist.file = json.dumps(temp)
                finallist.save()

                return JsonResponse({"status": 200,"message":"删除成功！"})
            else:
                return JsonResponse({"status": 400,"message":"索引下标非法,最大索引为:{},接收到的:{}".format(len(filedata)-1,aimindex)})
        else:
            if aimindex < len(filedata[0]):
                for i in range(len(filedata)):
                    filedata[i].pop(aimindex)
                finallist = Template.objects.get(id=int(aimlist.template_id))
                temp = json.loads(finallist.file)
                temp['file_data'] = json.dumps(filedata)
                finallist.file = json.dumps(temp)
                finallist.save()

                return JsonResponse({"status": 200,"message":"删除成功！"})
            else:
                return JsonResponse({"status": 400,"message":"索引下标非法,最大索引为:{},接收到的:{}".format(len(filedata[0])-1,aimindex)})

    def put(self, request):
        data = json.loads(request.body)
        # print(data["file_excel"])
        print(data)
        print(data['id'])
        prolist1 = ProjectList.objects.get(id=data['id'])
        aimlist = Template.objects.get(id=int(prolist1.template_id))
        # aimlist = Template.objects.get(id=data['id'])
        # file_dict = json.loads(aimlist.file)
        # 文件路径
        # pathUrl = os.path.join(BASE_DIR, 'static', 'template', file_dict["file_excel"])
        result = []
        for i in data['file_excel']:
            temp = []
            for j in range(1, len(i.values())):
                if j != 2:
                    temp.append(list(i.values())[j])
            result.append(temp)
        title = []
        for i in data['file_title']:
            title.append(i['title'])
        title = {
            "title": title
        }
        print(title["title"])
        ttt = json.loads(aimlist.file)
        ttt['file_data'] = json.dumps(result)
        aimlist.file_title = json.dumps(title)
        aimlist.file = json.dumps(ttt)
        aimlist.save()

        return JsonResponse({"status": 200, "message": "修改成功！","template_id":int(prolist1.template_id)})

# 入库信息
class StorageMessages(View):

    def get(self,req):

        try:
            # 第几页
            pagenum = int(req.GET.get('pagenum'))
            # 每页多少条
            pagesize = int(req.GET.get('pagesize'))
            # 获取修改时间

            update_time = req.GET.get('update_time')
            # 仓库id
            store_id=req.GET.get('store_id')
            if store_id==None:
                return JsonResponse({'message':'库存id不能为空','status':203})

            StoreDate=Store.objects.filter(id=store_id).all()

            lis=[]
            count=0
            if update_time == None:
                for i in StoreDate:
                    da = i.storagemessage_set.all().values()
                    lis = list(da)
                    lis = lis[((pagenum - 1) * pagesize):(pagenum * pagesize)]
                    count=len(lis)

            else:
                for i in StoreDate:

                    da = i.storagemessage_set.all().values()
                    for x in da:

                        # print(update_time in str(x['update_time']))
                        if update_time in str(x['update_time']):
                            lis.append(x)
                count = len(lis)
                lis=lis[((pagenum - 1) * pagesize):(pagenum * pagesize)]


            # lis = StorageMessage.objects.filter(update_time__contains=update_time).values()[
            #       ((pagenum - 1) * pagesize):(pagenum * pagesize)]
            # count = StorageMessage.objects.filter(update_time__contains=update_time).count()
        except:
            return JsonResponse({'status': 201, 'message': '请查看接口文档数据'})


        return JsonResponse({'status':200,"message":"获取成功！","data":list(lis),"count":count})
    def put(self,req):
        try:
            da=json.loads(req.body)
            StoreDate=Store.objects.filter(id=da['store_id']).all()
            for i in StoreDate:
                y=i.storagemessage_set.all().values()

                for x in y:

                    if x['id'] == da['id']:
                        StorageMessage.objects.filter(id=x['id']).update(**da)
                    # else:
                    #     return JsonResponse({'status': 202, 'message': '传入的id不存在'})
        except:

            return JsonResponse({'status': 201, 'message': '请查看接口文档数据'})

        return JsonResponse({'status': 200, 'message': '修改成功'})
    def delete(self,req):

        try:
            da = json.loads(req.body)
            StoreDate = Store.objects.filter(id=da['store_id']).all()
            for i in StoreDate:
                y = i.storagemessage_set.all().values()

                for x in y:

                    if x['id'] == da['id']:
                        StorageMessage.objects.filter(id=x['id']).delete()
        except:
            return JsonResponse({'status': 201, 'message': '请查看接口文档数据'})
        return JsonResponse({'status': 200, 'message': '删除成功'})

# 入库信息
class StorageRemovals(View):

    def get(self,req):

        try:
            # 第几页
            pagenum = int(req.GET.get('pagenum'))
            # 每页多少条
            pagesize = int(req.GET.get('pagesize'))
            # 获取修改时间

            update_time = req.GET.get('update_time')
            # 仓库id
            store_id=req.GET.get('store_id')
            if store_id==None:
                return JsonResponse({'message':'库存id不能为空','status':203})
            StoreDate=Store.objects.filter(id=store_id).all()

            lis=[]
            count=0
            if update_time == None:

                for i in StoreDate:
                    da = i.storageremoval_set.all().values()
                    lis = list(da)
                    lis = lis[((pagenum - 1) * pagesize):(pagenum * pagesize)]
                    count=len(lis)

            else:
                for i in StoreDate:

                    da = i.storageremoval_set.all().values()
                    for x in da:

                        # print(update_time in str(x['update_time']))
                        if update_time in str(x['update_time']):
                            lis.append(x)
                count = len(lis)
                lis=lis[((pagenum - 1) * pagesize):(pagenum * pagesize)]


            # lis = StorageMessage.objects.filter(update_time__contains=update_time).values()[
            #       ((pagenum - 1) * pagesize):(pagenum * pagesize)]
            # count = StorageMessage.objects.filter(update_time__contains=update_time).count()
        except:
            return JsonResponse({'status': 201, 'message': '请查看接口文档数据'})


        return JsonResponse({'status':200,"message":"获取成功！","data":list(lis),"count":count})

    def put(self,req):
        try:
            da=json.loads(req.body)
            StoreDate=Store.objects.filter(id=da['store_id']).all()
            for i in StoreDate:
                y=i.storageremoval_set.all().values()

                for x in y:

                    if x['id'] == da['id']:
                        StorageRemoval.objects.filter(id=x['id']).update(**da)
                    # else:
                    #     return JsonResponse({'status': 202, 'message': '传入的id不存在'})
        except:

            return JsonResponse({'status': 201, 'message': '请查看接口文档数据'})

        return JsonResponse({'status': 200, 'message': '修改成功'})
    def delete(self,req):

        try:
            da = json.loads(req.body)
            StoreDate = Store.objects.filter(id=da['store_id']).all()
            for i in StoreDate:
                y = i.storageremoval_set.all().values()

                for x in y:

                    if x['id'] == da['id']:
                        StorageRemoval.objects.filter(id=x['id']).delete()
        except:
            return JsonResponse({'status': 201, 'message': '请查看接口文档数据'})
        return JsonResponse({'status': 200, 'message': '删除成功'})
def AllTemplate(request):
    data = Template.objects.all().values()
    return JsonResponse({
        'status': 200,
        'message': '成功',
        'data': list(data),

    })

class Test(View):
    def post(self,req):
        # dat=json.loads(req.body)
        data = req.body
        if data:
            da = json.loads(data)
            print( da)
            print(type(da))
        else:
            print("没有")
            return JsonResponse({"msg":"没有body","status":"400"})
        return JsonResponse({"msg":"返回成功","status":"200"})
